<template>
  <div>

    <div class="d-flex align-center justify-space-between mb-3">
      <div class="text-h6 font-weight-bold brand-logo">User Management</div>
      <div class="d-flex align-center">
        <v-text-field
          v-model.trim="queryInput"
          class="mr-2"
          style="width: 280px;"
          outlined
          dense
          clearable
          hide-details
          label="Search (e.g. username:alice email:x@x.com)"
          append-icon="mdi-magnify"
          @keyup.enter="onSearchFromInput"
          @click:append="onSearchFromInput"
          @click:clear="onResetInput"
        />
        <v-btn class="mr-2" outlined>Export</v-btn>
        <v-btn color="primary" dark @click="openAddDialog">+ Add User</v-btn>
      </div>
    </div>

    <v-data-table
      :headers="headers"
      :items="users"
      :items-per-page="pageSize"
      :page.sync="pageNum"
      :server-items-length="total"
      :loading="loading"
      class="elevation-1"
      dense
      @update:page="onPageChange"
      @update:items-per-page="onPageSizeChange"
      @click:row="onRowClick"
    >
      <template v-slot:item.id="{ item }">#{{ item.id }}</template>
      <template v-slot:item.isActive="{ item }">
        <v-chip small :color="item.isActive ? 'green lighten-4' : 'red lighten-4'" :text-color="item.isActive ? 'green darken-2' : 'red darken-2'">
          {{ item.isActive ? 'Active' : 'Inactive' }}
        </v-chip>
      </template>
      <template v-slot:item.actions="{ item }">
        <v-btn x-small outlined color="primary" class="mr-1" @click="openEditDialog(item)">Edit</v-btn>
        <v-btn x-small outlined color="error" @click="confirmDelete(item)">Delete</v-btn>
      </template>
    </v-data-table>

    <!-- Add User Dialog -->
    <v-dialog v-model="addDialog" max-width="520px">
      <v-card>
        <v-card-title class="font-weight-bold">Add User</v-card-title>
        <v-divider></v-divider>
        <v-card-text>
          <v-form ref="addForm" v-model="addFormValid">
            <v-text-field
              v-model="newUser.username"
              label="Username"
              outlined
              dense
              :rules="[rules.required]"
            />
            <v-text-field
              v-model="newUser.email"
              label="Email"
              outlined
              dense
              :rules="[rules.required, rules.email]"
            />
            <v-select
              v-model="newUser.roleCode"
              :items="roleOptions"
              item-text="name"
              item-value="roleCode"
              label="Role"
              outlined
              dense
              :rules="[rules.required]"
            />
            <div class="d-flex align-center mt-2">
              <v-switch v-model="newUser.isActive" inset label="Active" class="ma-0"></v-switch>
            </div>
          </v-form>
        </v-card-text>
        <v-divider></v-divider>
        <v-card-actions class="justify-end">
          <v-btn text @click="closeAddDialog">Cancel</v-btn>
          <v-btn color="primary" dark @click="submitAddUser">Save</v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>

    <!-- Edit User Dialog -->
    <v-dialog v-model="editDialog" max-width="520px">
      <v-card>
        <v-card-title class="font-weight-bold">Edit User</v-card-title>
        <v-divider></v-divider>
        <v-card-text>
          <v-form ref="editForm" v-model="editFormValid">
            <v-text-field v-model="editUser.username" label="Username" outlined dense :rules="[rules.required]" />
            <v-text-field v-model="editUser.email" label="Email" outlined dense :rules="[rules.required, rules.email]" />
            <v-select v-model="editUser.roleCode" :items="roleOptions" item-text="name" item-value="roleCode" label="Role" outlined dense :rules="[rules.required]" />
            <div class="d-flex align-center mt-2">
              <v-switch v-model="editUser.isActive" inset label="Active" class="ma-0" />
            </div>
          </v-form>
        </v-card-text>
        <v-divider></v-divider>
        <v-card-actions class="justify-end">
          <v-btn text @click="closeEditDialog">Cancel</v-btn>
          <v-btn color="primary" dark @click="submitEditUser">Save</v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>

    <!-- User Detail Dialog -->
    <v-dialog v-model="detailDialog" max-width="700px">
      <v-card>
        <v-card-title class="font-weight-bold">User Detail</v-card-title>
        <v-divider></v-divider>
        <v-card-text>
          <div class="mb-3">
            <div><strong>ID:</strong> {{ detailUser.id }}</div>
            <div><strong>Username:</strong> {{ detailUser.username }}</div>
            <div><strong>Email:</strong> {{ detailUser.email }}</div>
            <div><strong>Roles:</strong>
              <span v-if="Array.isArray(detailUser.roles) && detailUser.roles.length">
                {{ detailUser.roles.map(r => r.name || r.roleCode).join(', ') }}
              </span>
              <span v-else>{{ detailUser.roleCode || '-' }}</span>
            </div>
            <div><strong>Status:</strong> {{ detailUser.isActive ? 'Active' : 'Inactive' }}</div>
          </div>
        </v-card-text>
        <v-divider></v-divider>
        <v-card-actions class="justify-end">
          <v-btn text @click="detailDialog=false">Close</v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>
  </div>
</template>

<script>
export default {
  name: 'UserPage',
  data() {
    return {
      headers: [
        { text: 'USER ID', value: 'id' },
        { text: 'USERNAME', value: 'username' },
        { text: 'EMAIL', value: 'email' },
        { text: 'ROLE', value: 'roleCode' },
        { text: 'STATUS', value: 'isActive' },
        { text: 'LAST LOGIN', value: 'lastLogin' },
        { text: 'ACTIONS', value: 'actions', sortable: false }
      ],
      users: [],
      total: 0,
      pageNum: 1,
      pageSize: 10,
      loading: false,
      queryInput: '',
      query: { username: '', email: '', roleCode: '', isActive: '' },
      statusOptions: [
        { text: 'Active', value: true },
        { text: 'Inactive', value: false }
      ],
      addDialog: false,
      addFormValid: false,
      newUser: { username: '', email: '', roleCode: '', isActive: true },
      editDialog: false,
      editFormValid: false,
      editUser: { id: '', username: '', email: '', roleCode: '', isActive: true },
      roleOptions: [],
      detailDialog: false,
      detailUser: {},
      rules: {
        required: v => !!(v && String(v).trim()) || 'Required',
        email: v => !v || /.+@.+\..+/.test(v) || 'Invalid email'
      }
    }
  },
  created() {
    this.fetchUsers()
    this.fetchRoleOptions()
  },
  methods: {
    async fetchUsers() {
      this.loading = true
      try {
        const q = { ...this.query }
        Object.keys(q).forEach(k => { if (q[k] === '' || q[k] === null || typeof q[k] === 'undefined') delete q[k] })
        const res = await this.$api.user.getUsers({ pageNum: this.pageNum, pageSize: this.pageSize, ...q })
        // Compatible with both { list, total } and { data: { list, total } }
        const payload = res && (res.data || res)
        const list = payload.list || payload.items || []
        this.users = list.map(u => ({
          ...u,
          roleCode: u.roleCode || u.role || '',
          isActive: typeof u.isActive !== 'undefined' ? u.isActive : !!u.active
        }))
        this.total = Number(payload.total || payload.totalCount || 0)
      } catch (e) {
        // eslint-disable-next-line no-console
        console.error('Failed to fetch users', e)
      } finally {
        this.loading = false
      }
    },
    onSearch() {
      this.pageNum = 1
      this.fetchUsers()
    },
    onReset() {
      this.query = { username: '', email: '', roleCode: '', isActive: '' }
      this.pageNum = 1
      this.fetchUsers()
    },
    onSearchFromInput() {
      const params = this.parseQueryInput(this.queryInput)
      this.query = { username: '', email: '', roleCode: '', isActive: '' , ...params }
      this.pageNum = 1
      this.fetchUsers()
    },
    onResetInput() {
      this.queryInput = ''
      this.onReset()
    },
    parseQueryInput(input) {
      const params = {}
      if (!input || !input.trim()) return params
      const tokens = input.trim().split(/\s+/)
      tokens.forEach(t => {
        const idx = t.indexOf(':')
        if (idx > 0) {
          const key = t.slice(0, idx).toLowerCase()
          const valRaw = t.slice(idx + 1)
          const val = valRaw === 'true' ? true : valRaw === 'false' ? false : valRaw
          if (['user','username'].includes(key)) params.username = val
          else if (['mail','email'].includes(key)) params.email = val
          else if (['role','rolecode'].includes(key)) params.roleCode = val
          else if (['active','status','isactive'].includes(key)) params.isActive = val
        } else {
          // Bare keyword: use for username/email/roleCode to broaden recall
          if (!params.username) params.username = t
          if (!params.email) params.email = t
          if (!params.roleCode) params.roleCode = t
        }
      })
      return params
    },
    async fetchRoleOptions() {
      try {
        const res = await this.$api.role.getRoles({ pageNum: 1, pageSize: 1000 })
        const payload = res && (res.data || res)
        const items = payload.list || payload.items || []
        this.roleOptions = items
      } catch (e) {
        // eslint-disable-next-line no-console
        console.error('Failed to fetch role options', e)
      }
    },
    async confirmDelete(item) {
      if (!item || !item.id) return
      const ok = window.confirm(`Delete user "${item.username}"?`)
      if (!ok) return
      try {
        await this.$api.user.deleteUser(item.id)
        this.fetchUsers()
      } catch (e) {
        // eslint-disable-next-line no-console
        console.error('Failed to delete user', e)
      }
    },
    onPageChange(p) {
      this.pageNum = p
      this.fetchUsers()
    },
    onPageSizeChange(size) {
      this.pageSize = size
      this.pageNum = 1
      this.fetchUsers()
    },
    openAddDialog() { this.addDialog = true },
    closeAddDialog() {
      this.addDialog = false
      this.$nextTick(() => { if (this.$refs.addForm) this.$refs.addForm.resetValidation() })
    },
    openEditDialog(item) {
      this.editUser = { ...item }
      this.editDialog = true
    },
    closeEditDialog() {
      this.editDialog = false
      this.$nextTick(() => { if (this.$refs.editForm) this.$refs.editForm.resetValidation() })
    },
    async submitAddUser() {
      if (!this.$refs.addForm || !this.$refs.addForm.validate()) return
      try {
        await this.$api.user.createUser({
          username: this.newUser.username.trim(),
          email: this.newUser.email.trim(),
          roleCode: this.newUser.roleCode,
          isActive: !!this.newUser.isActive
        })
        this.newUser = { username: '', email: '', roleCode: '', isActive: true }
        this.closeAddDialog()
        this.fetchUsers()
      } catch (e) {
        // eslint-disable-next-line no-console
        console.error('Failed to create user', e)
      }
    },
    async submitEditUser() {
      if (!this.$refs.editForm || !this.$refs.editForm.validate()) return
      try {
        await this.$api.user.updateUser(this.editUser.id, {
          username: this.editUser.username.trim(),
          email: this.editUser.email.trim(),
          roleCode: this.editUser.roleCode,
          isActive: !!this.editUser.isActive
        })
        this.closeEditDialog()
        this.fetchUsers()
      } catch (e) {
        // eslint-disable-next-line no-console
        console.error('Failed to update user', e)
      }
    },
    onRowClick(item, event) {
      if (event && event.detail >= 2) {
        this.openDetail(item)
      }
    },
    async openDetail(item) {
      this.detailDialog = true
      try {
        const res = await this.$api.user.getUserById(item.id)
        this.detailUser = (res && (res.data || res)) || item
      } catch (e) {
        // eslint-disable-next-line no-console
        console.error('Failed to load user detail', e)
        this.detailUser = item
      }
    }
  }
}
</script>
<style scoped>
</style>

